# -*- coding: utf-8 -*-
from anytree.resolver import (
    Resolver,
    ResolverError,
    ChildResolverError,
    _getattr
)


class PatchResolver(Resolver):
    """docstring for PatchResolver"""
    def __init__(self, pathattr='name'):
        super(PatchResolver, self).__init__(pathattr)

    def get(self, node, path):
        node, parts = self.__start(node, path)
        for part in parts:
            if part == "..":
                node = node.parent
            elif part in ("", "."):
                pass
            else:
                node = self.__get(node, part)
        return node

    def __get(self, node, name):
        for child in node.children:
            child_name = _getattr(child, self.pathattr)
            if isinstance(name, str) and isinstance(child_name, bytes) and bytes != str:
                name = name.encode('utf-8')
            if child_name == name:
                return child
        raise ChildResolverError(node, name, self.pathattr)

    def __start(self, node, path):
        sep = node.separator
        parts = path.split(sep)
        if path.startswith(sep):
            node = node.root
            rootpart = _getattr(node, self.pathattr)
            parts.pop(0)
            if not parts[0]:
                msg = "root node missing. root is '%s%s'."
                raise ResolverError(node, "", msg % (sep, str(rootpart)))
            elif parts[0] != rootpart:
                msg = "unknown root node '%s%s'. root is '%s%s'."
                raise ResolverError(node, "", msg % (sep, parts[0], sep, str(rootpart)))
            parts.pop(0)
        return node, parts